package com.iemes.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import com.iemes.entity.FlowStepFormMap;
import com.iemes.entity.SfcStepFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.UDefinedDataValueFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.BaseExtMapper;
import com.iemes.mapper.workProcess.WorkPodPanelMapper;
import com.iemes.service.CommonService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class CommonServiceImpl implements CommonService {

	@Inject
	private BaseExtMapper baseMapper;
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@Inject
	private WorkPodPanelMapper WorkPodPanelMapper;

	@Override
	@Transactional
	public void saveUDefinedDataValueS(String id, String userDefinedValues) throws BusinessException {
		try {
			baseMapper.deleteByAttribute("data_type_detail_id", id, UDefinedDataValueFormMap.class);

			// 插入自定义数据字段表
			if (!StringUtils.isEmpty(userDefinedValues)) {
				JSONArray jsonArray = JSONArray.fromObject(userDefinedValues);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject objectRow = jsonArray.getJSONObject(i);
					JSONObject objectFieldCell = objectRow.getJSONObject("key");
					JSONObject objectValueCell = objectRow.getJSONObject("value");

					String filedId = objectFieldCell.getString("value");
					String filedValue = objectValueCell.getString("value");

					UDefinedDataValueFormMap uDefinedDataValueFormMapNew = new UDefinedDataValueFormMap();
					uDefinedDataValueFormMapNew.put("id", UUIDUtils.getUUID());
					uDefinedDataValueFormMapNew.put("site_id", ShiroSecurityHelper.getSiteId());
					uDefinedDataValueFormMapNew.put("data_type_detail_id", id);
					uDefinedDataValueFormMapNew.put("udefined_data_filed_id", filedId);
					uDefinedDataValueFormMapNew.put("value", filedValue);
					uDefinedDataValueFormMapNew.put("create_user", ShiroSecurityHelper.getCurrentUsername());
					uDefinedDataValueFormMapNew.put("create_time", DateUtils.getStringDateTime());

					baseMapper.addEntity(uDefinedDataValueFormMapNew);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("自定义数据字段保存失败！"+e.getMessage());
		}
	}
	
	@Override
	public String getShoporderStatusStr(int status) throws BusinessException {
		try {
			// 工单状态：0、创建；1、已下达；2、生产中；3、已完成；4、关闭；5、挂起；6、已删除
			switch (status) {
			case 0:
				return "创建";
			case 1:
				return "已下达";
			case 2:
				return "生产中";
			case 3:
				return "已完成";
			case 4:
				return "关闭";
			case 5:
				return "挂起";
			case 6:
				return "已删除";
			default:
				return "";
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("工单状态转换失败！" + e.getMessage());
		}
	}
	
	@Override
	public String getSfcStatusStr(int status) throws BusinessException {
		try {
			// SFC状态：0、创建；1、生产中；2、已完成；3、报废；4、记录不良状态中
			switch (status) {
			case 0:
				return "创建";
			case 1:
				return "生产中";
			case 2:
				return "已完成";
			case 3:
				return "报废";
			case 4:
				return "记录不良状态中";
			default:
				return "";
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("sfc状态转换失败！" + e.getMessage());
		}
	}
	
	@Override
	public String getSfcStepStatusStr(int status) throws BusinessException {
		try {
			// SFC步骤状态：0、创建；1、生产中；2、已完成；3、报废；4、记录不良状态中
			switch (status) {
			case 0:
				return "创建";
			case 1:
				return "生产中";
			case 2:
				return "已完成";
			case 3:
				return "报废";
			case 4:
				return "记录不良状态中";
			default:
				return "";
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("sfc步骤状态转换失败！" + e.getMessage());
		}
	}

	@Override
	public List<FlowStepFormMap> getNextOperation(String operation_id, String process_workflow_id) throws BusinessException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("operation_id", operation_id);
		map.put("process_workflow_id", process_workflow_id);
		List<Map<String,String>> nextOperation = WorkPodPanelMapper.getNextOperation(map);
		List<FlowStepFormMap> list = new ArrayList<FlowStepFormMap>();
		for (Map<String,String> operation : nextOperation) {
			FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
			flowStepFormMap.putAll(operation);
			list.add(flowStepFormMap);
		}
		return list;
	}

	@Override
	public ShoporderFormMap isLastSfcOnShoporder(String shoporder_id) throws BusinessException {
		List<ShoporderFormMap> list = baseMapper.findByAttribute("id", shoporder_id, ShoporderFormMap.class);
		if (!ListUtils.isNotNull(list)) {
			String msg = "未能检索到对应的工单信息，请确认信息是否无误";
			log.error(msg);
			throw new BusinessException(msg);
		}
		ShoporderFormMap shoporderFormMap = list.get(0);
		int num = shoporderFormMap.getInt("shoporder_number");
		
		ShopOrderSfcFormMap shopOrderSfcFormMap3 = new ShopOrderSfcFormMap();
		StringBuffer where = new StringBuffer();
		where.append(" where 1=1 ");
		where.append(" and shoporder_id = '" + shoporder_id + "' ");
		where.append(" and sfc_status in ('2','3')");
		shopOrderSfcFormMap3.put("where", where.toString());
		List<ShopOrderSfcFormMap> listShopOrderSfcFormMap2 = baseMapper.findByWhere(shopOrderSfcFormMap3);
		if (listShopOrderSfcFormMap2.size()==num) {
			return shoporderFormMap;
		}
		return null;
	}

	@Override
	public SfcStepFormMap getLastSfcStep(String sfc) throws BusinessException {
		SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
		sfcStepFormMap.put("sfc", sfc);
		sfcStepFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		sfcStepFormMap.put("orderby", " order by seq desc");
		
		List<SfcStepFormMap> list = baseMapper.findByNames(sfcStepFormMap);
		if (!ListUtils.isNotNull(list)) {
			String msg = "未能检索到SFC："+sfc+"的相关步骤信息";
			log.error(msg);
			throw new BusinessException(msg);
		}
		return list.get(0);
	}

	@Override
	public List<FlowStepFormMap> getNextRepairOperation(String operation_id, String process_workflow_id)
			throws BusinessException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("operation_id", operation_id);
		map.put("process_workflow_id", process_workflow_id);
		List<Map<String,String>> nextOperation = WorkPodPanelMapper.getNextRepairOperation(map);
		List<FlowStepFormMap> list = new ArrayList<FlowStepFormMap>();
		for (Map<String,String> operation : nextOperation) {
			FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
			flowStepFormMap.putAll(operation);
			list.add(flowStepFormMap);
		}
		return list;
	}
	
}
